import json

from bson.objectid import ObjectId

from api_base import *


class APIMyHandler(APIBaseHandler):
    OPTIONAL_FIELDS = ['realname', 'class', 'uid', 'password']

    @check_role(RoleStudent)
    async def get(self):
        '''
        获取我的信息
        '''
        res = await self.db.users.find_one({'username': self.current_user})
        if not res:
            self.write_json({'info': 'err'})
            return
        res.pop('_id')
        res.pop('password')
        self.write_json({'info': 'ok', 'result': res})

    @check_role(RoleStudent)
    async def post(self):
        '''
        修改我的信息
        '''
        try:
            js = json.loads(self.request.body)
        except:
            self.write_json({'info': 'json_error'})
            return
        to_update = {k: js[k] for k in self.OPTIONAL_FIELDS if js.get(k)}
        res = await self.db.users.update_one({'username': self.current_user}, {'$set': to_update})
        self.write_json({'info': 'ok',
                         'matched': res.matched_count,
                         'modified': res.modified_count})
